/*
 * Copyright 2016-2017 lei.xu<xulei2008xulei@163.com>.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.san21go.jfinfunc.financ.norm;

import org.san21go.jfinfunc.AbstractFunction;
import org.san21go.jfinfunc.FinFuncRuntimeException;
import org.san21go.jfinfunc.jfinfunc.math.AVERAGE;

/**
 * 特雷诺指数（Treynor）：是以基金收益的系统风险作为基金绩效调整的因子，反映基金承担单位系统风险所获得的超额收益。指数值越大，
 * 承担单位系统风险所获得的超额收益越高。
 * 
 * @author xulei
 *
 */
public class Treynor extends AbstractFunction<Double> {
	/**
	 * 策略每日收益
	 */
	private double[] yieldRates;
	/**
	 * 基准每日收益
	 */
	private double[] baseRates;
	/**
	 * 无风险收益率
	 */
	private double[] freeRiskRates;

	public Treynor(double[] yieldRates, double[] baseRates, double[] freeRiskRates) {
		super();
		this.yieldRates = yieldRates;
		this.baseRates = baseRates;
		this.freeRiskRates = freeRiskRates;
	}

	@Override
	public Double evaluate() {

		if (yieldRates == null || freeRiskRates == null || baseRates == null || baseRates.length == 0
				|| yieldRates.length == 0 || freeRiskRates.length == 0) {
			throw new FinFuncRuntimeException("参数错误");
		}
		if (yieldRates.length != baseRates.length || freeRiskRates.length != yieldRates.length) {
			throw new FinFuncRuntimeException("参数错误");
		}

		// Rp=策略年化收益率
		double Rp = new AVERAGE(yieldRates).evaluate();
		// Rf=无风险收益率
		double Rf = new AVERAGE(freeRiskRates).evaluate();
		// Beta系数
		double βp = new Beta(yieldRates, baseRates).evaluate();

		if (Double.compare(βp, 0) == 0) {
			return 0D;
		}

		double treynor = (Rp - Rf) / βp;
		return treynor;
	}

}
